import React, { useEffect, useRef, useMemo } from 'react';
import { Card, Col, Row, Skeleton, Statistic, Progress, Divider, Alert, Tag } from 'antd';
import { EyeOutlined, CheckCircleOutlined, FileAddOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import _ from 'lodash';
import { getNewsStats, getViewStatistics, getStarStatistics, getCompleteStatistics } from '../../../api/newsApi';
import { useQuery } from '@tanstack/react-query';
import './Home.scss';

// 新闻统计数据类型
interface NewsStats {
  total: number;
  draft: number;
  auditing?: number;  // 后端使用auditing，而不是pending
  auditPass?: number;
  auditReject?: number;
  published: number;
  unpublished?: number;
  sunset?: number;
  // 可选字段，可能在后端不存在
  pending?: number;
  mostViewedCategory?: string;
  viewsToday?: number;
  viewsWeek?: number;
  viewsMonth?: number;
  userStats?: {
    totalPublished?: number;
    pendingAudit?: number;
    pendingPublish?: number;
    mostPopular?: {
      title?: string;
      views?: number;
    }
  }
  // MongoDB特有字段
  _id?: string;
  __v?: number;
}

// 定义echarts颜色函数参数类型
interface EChartsColorParams {
  dataIndex: number;
  seriesIndex: number;
  data: number | object;
  value: number;
}

// 定义阅读统计数据类型 - 与API完全匹配
interface ViewStats {
  today: number;
  todayCompare: number;
  week: number;
  weekCompare: number;
  month: number;
  monthCompare: number;
  __v?: number; // MongoDB版本号
}

// 定义点赞统计数据类型 - 与API完全匹配
interface StarStats {
  today: number;
  todayCompare: number;
  week: number;
  weekCompare: number;
  month: number;
  monthCompare: number;
  __v?: number; // MongoDB版本号
}

// 后端统计项类型
interface StatItem {
  _id: number | string; // MongoDB可能返回字符串ID
  count: number;
}

// 分类统计项
interface CategoryStatItem {
  _id?: string;           // MongoDB的ObjectId
  categoryId: string;
  categoryName: string;
  count: number;
}

// 完整的后端统计数据结构 - 与API完全匹配
interface CompleteStatsResponse {
  categoryStats: CategoryStatItem[];
  auditStats: StatItem[];
  publishStats: StatItem[];
  total: Array<{count: number}>;
  views?: ViewStats;
  stars?: StarStats;
  __v?: number; // MongoDB版本号
}

const Home: React.FC = () => {
  // 处理后端数据，使其符合前端预期
  const processNewsStats = (backendData: unknown): NewsStats => {
    console.log('后端返回的统计数据:', backendData);
    
    // 转换为Record类型以便安全访问
    const data = backendData as Record<string, unknown>;
    
    // 基础数据处理
    const processedData: NewsStats = {
      total: Number(data.total) || 0,
      draft: Number(data.draft) || 0,
      published: Number(data.published) || 0,
      // 如果后端使用auditing，而前端使用pending，做一个映射
      pending: Number(data.auditing) || 0,
      // 添加其他可能缺少的字段，提供默认值
      viewsToday: 0,
      viewsWeek: 0,
      viewsMonth: 0,
      mostViewedCategory: '暂无数据',
      // 保留MongoDB特有字段
      _id: data._id as string,
      __v: data.__v as number
    };
    
    return processedData;
  };
  
  // 查询新闻统计数据
  const { data: statsData, isLoading: statsLoading } = useQuery({
    queryKey: ['newsStats'],
    queryFn: getNewsStats,
    staleTime: 0, // 禁用缓存，每次都实时获取数据
    refetchOnWindowFocus: false
  });

  // 查询阅读量统计数据
  const { data: viewStatsData, isLoading: viewStatsLoading } = useQuery({
    queryKey: ['viewStats'],
    queryFn: getViewStatistics,
    staleTime: 0, // 禁用缓存，每次都实时获取数据
    refetchOnWindowFocus: false
  });

  // 查询点赞统计数据
  const { data: starStatsData, isLoading: starStatsLoading } = useQuery({
    queryKey: ['starStats'],
    queryFn: getStarStatistics,
    staleTime: 0, // 禁用缓存，每次都实时获取数据
    refetchOnWindowFocus: false
  });
  
  // 查询完整统计数据（包含所有统计信息）
  const { data: completeStatsData } = useQuery({
    queryKey: ['completeStats'],
    queryFn: getCompleteStatistics,
    staleTime: 0, // 禁用缓存，每次都实时获取数据
    refetchOnWindowFocus: false
  });
  
  // 新闻统计数据
  const newsStats = useMemo<NewsStats | undefined>(() => {
    // 使用完整统计数据
    if (completeStatsData) {
      // API直接返回了数据对象，不需要通过.data访问
      const data = completeStatsData as CompleteStatsResponse;
      // 获取状态统计
      const total = data.total?.[0]?.count || 0;
      
      // 发布状态：0-草稿，1-待发布, 2-已发布，3-已下线
      const draftCount = data.publishStats?.find(item => String(item._id) === '0')?.count || 0;
      const pendingPublishCount = data.publishStats?.find(item => String(item._id) === '1')?.count || 0;
      const publishedCount = data.publishStats?.find(item => String(item._id) === '2')?.count || 0;
      const sunsetCount = data.publishStats?.find(item => String(item._id) === '3')?.count || 0;
      
      // 审核状态：0-未审核，1-审核中，2-已通过，3-未通过
      const pendingCount = data.auditStats?.find(item => String(item._id) === '1')?.count || 0;
      const auditPassCount = data.auditStats?.find(item => String(item._id) === '2')?.count || 0;
      const auditRejectCount = data.auditStats?.find(item => String(item._id) === '3')?.count || 0;
      
      return {
        total,
        draft: draftCount,
        pending: pendingCount,
        auditPass: auditPassCount,
        auditReject: auditRejectCount,
        published: publishedCount,
        unpublished: pendingPublishCount,
        sunset: sunsetCount,
        // 添加阅读量相关数据
        viewsToday: data.views?.today || 0,
        viewsWeek: data.views?.week || 0,
        viewsMonth: data.views?.month || 0,
        // 保留MongoDB版本号
        __v: data.__v
      };
    }
    
    // 如果没有获取到完整数据，尝试使用单独的统计数据
    if (statsData) {
      // API直接返回了数据对象，不需要通过.data访问
      return processNewsStats(statsData);
    }
    
    return undefined;
  }, [completeStatsData, statsData]);
  
  // 阅读量统计数据 - 修复类型问题
  const viewStats = useMemo<ViewStats | undefined>(() => {
    // 优先使用完整统计数据中的views部分
    if (completeStatsData) {
      // API直接返回了数据对象，不需要通过.data访问
      const data = completeStatsData as CompleteStatsResponse;
      if (data.views) {
        return data.views;
      }
    }
    
    // 如果没有完整数据，尝试使用独立的阅读量统计
    if (viewStatsData) {
      // 确保返回的数据是符合ViewStats类型的
      const data = viewStatsData as unknown;
      if (data && typeof data === 'object') {
        return data as ViewStats;
      }
    }
    
    // 返回默认值，确保类型安全
    return undefined;
  }, [completeStatsData, viewStatsData]);
  
  // 点赞统计数据 - 修复类型问题
  const starStats = useMemo<StarStats | undefined>(() => {
    // 优先使用完整统计数据中的stars部分
    if (completeStatsData) {
      // API直接返回了数据对象，不需要通过.data访问
      const data = completeStatsData as CompleteStatsResponse;
      if (data.stars) {
        return data.stars;
      }
    }
    
    // 如果没有完整数据，尝试使用独立的点赞量统计
    if (starStatsData) {
      // 确保返回的数据是符合StarStats类型的
      const data = starStatsData as unknown;
      if (data && typeof data === 'object') {
        return data as StarStats;
      }
    }
    
    // 返回默认值，确保类型安全
    return undefined;
  }, [completeStatsData, starStatsData]);
  
  // 发布率计算
  const publishRate = useMemo(() => {
    if (!newsStats) return 0;
    if (newsStats.total === 0) return 0;
    return Math.round((newsStats.published / newsStats.total) * 100);
  }, [newsStats]);
  
  const pieChartRef = useRef<HTMLDivElement>(null);
  const barChartRef = useRef<HTMLDivElement>(null);
  
  // 渲染饼图
  useEffect(() => {
    if (!pieChartRef.current || !newsStats) return;
    
    try {
      const chartInstance = echarts.init(pieChartRef.current);
      
      // 准备数据
      const data = [
        { name: '已发布', value: newsStats.published || 0 },
        { name: '待审核', value: newsStats.pending || 0 },
        { name: '草稿', value: newsStats.draft || 0 },
        { name: '已下线', value: newsStats.sunset || 0 }
      ].filter(item => item.value > 0); // 过滤掉数量为0的数据
      
      // 如果没有有效数据，不进行渲染
      if (!data.length) {
        return;
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: data.map(item => item.name)
        },
        series: [
          {
            name: '新闻状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data,
            animationType: 'scale',
            animationEasing: 'elasticOut'
          }
        ],
        color: (params: EChartsColorParams) => {
          // 自定义颜色
          const colors = ['#52c41a', '#1890ff', '#faad14', '#f5222d'];
          return colors[params.dataIndex % colors.length];
        }
      };
      
      chartInstance.setOption(option);
      
      // 响应窗口大小变化
      const handleResize = () => {
        chartInstance.resize();
      };
      
      window.addEventListener('resize', handleResize);
      
      return () => {
        window.removeEventListener('resize', handleResize);
        chartInstance.dispose();
      };
    } catch (error) {
      console.error('饼图渲染失败:', error);
    }
  }, [newsStats]);
  
  // 渲染柱状图
  useEffect(() => {
    if (!barChartRef.current || !completeStatsData) return;
    
    try {
      const chartInstance = echarts.init(barChartRef.current);
      
      // 从后端数据中提取出分类统计
      const data = completeStatsData as CompleteStatsResponse;
      const categoryStats = data.categoryStats || [];
      
      // 如果没有分类数据，不进行渲染
      if (!categoryStats.length) {
        return;
      }
      
      // 按照数量排序并限制显示数量
      const sortedStats = _.sortBy(categoryStats, 'count').reverse().slice(0, 6);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: sortedStats.map((item: CategoryStatItem) => item.categoryName || '未知分类'),
          axisLabel: {
            rotate: 45,
            interval: 0
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '新闻数量',
            type: 'bar',
            barWidth: '60%',
            data: sortedStats.map((item: CategoryStatItem) => item.count || 0),
            itemStyle: {
              color: (params: EChartsColorParams) => {
                const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#eb2f96'];
                return colors[params.dataIndex % colors.length];
              }
            }
          }
        ]
      };
      
      chartInstance.setOption(option);
      
      // 响应窗口大小变化
      const handleResize = () => {
        chartInstance.resize();
      };
      
      window.addEventListener('resize', handleResize);
      
      return () => {
        window.removeEventListener('resize', handleResize);
        chartInstance.dispose();
      };
    } catch (error) {
      console.error('柱状图渲染失败:', error);
    }
  }, [completeStatsData]);
  
  return (
    <div className="dashboard-wrapper">
      {/* 数据统计面板 */}
      <div className="dashboard-section">
        <h2><FileAddOutlined /> 全局数据统计</h2>
        
        {/* 一行两列布局：左侧新闻发布统计，右侧上下排列阅读情况和点赞情况 */}
        <Row gutter={16}>
          {/* 左侧：新闻发布统计 */}
          <Col span={8}>
            <Card title="新闻发布统计" bordered>
              {statsLoading ? (
                <Skeleton active paragraph={{ rows: 4 }} />
              ) : (
                <>
                  <Alert
                    message={`系统总共有 ${newsStats?.total || 0} 条新闻`}
                    type="info"
                    showIcon
                    style={{ marginBottom: '16px' }}
                  />
                  
                  <div className="progress-item">
                    <span>已发布率</span>
                    <Progress
                      percent={publishRate}
                      status={publishRate > 80 ? "success" : (publishRate > 50 ? "active" : "exception")}
                    />
                  </div>
                  
                  <Divider style={{ margin: '12px 0' }} />
                  
                  <div className="stat-tags">
                    <Tag color="blue">已发布: {newsStats?.published || 0}</Tag>
                    <Tag color="gold">待审核: {newsStats?.pending || 0}</Tag>
                    <Tag color="cyan">草稿箱: {newsStats?.draft || 0}</Tag>
                  </div>
                 
                 <Divider style={{ margin: '12px 0' }} />
                 
                 <div className="stat-info">
                   <p><CheckCircleOutlined /> 最受欢迎分类: {newsStats?.mostViewedCategory || '暂无数据'}</p>
                  </div>
                </>
              )}
            </Card>
          </Col>
          
          {/* 右侧：阅读情况和点赞情况上下排列 */}
          <Col span={16}>
            {/* 上方：阅读情况统计 */}
            <Card title="阅读情况统计" bordered style={{ marginBottom: '16px' }}>
              {viewStatsLoading ? (
                <Skeleton active paragraph={{ rows: 4 }} />
              ) : (
                <Row gutter={16}>
                  <Col span={8}>
                    <Statistic
                      title="今日阅读量"
                      value={viewStats?.today || 0}
                      valueStyle={{ color: '#1890ff' }}
                      prefix={<EyeOutlined />}
                    />
                    <div className="view-growth">
                      较昨日: <span className={viewStats?.todayCompare && viewStats.todayCompare > 0 ? "up" : "down"}>
                        {viewStats?.todayCompare && viewStats.todayCompare > 0 ? "+" : ""}{viewStats?.todayCompare || 0}%
                      </span>
                    </div>
                  </Col>
                  
                  <Col span={8}>
                    <Statistic
                      title="本周阅读量"
                      value={viewStats?.week || 0}
                      valueStyle={{ color: '#52c41a' }}
                      prefix={<EyeOutlined />}
                    />
                    <div className="view-growth">
                      较上周: <span className={viewStats?.weekCompare && viewStats.weekCompare > 0 ? "up" : "down"}>
                        {viewStats?.weekCompare && viewStats.weekCompare > 0 ? "+" : ""}{viewStats?.weekCompare || 0}%
                      </span>
                    </div>
                  </Col>
                  
                  <Col span={8}>
                    <Statistic
                      title="本月阅读量"
                      value={viewStats?.month || 0}
                      valueStyle={{ color: '#722ed1' }}
                      prefix={<EyeOutlined />}
                    />
                    <div className="view-growth">
                      较上月: <span className={viewStats?.monthCompare && viewStats.monthCompare > 0 ? "up" : "down"}>
                        {viewStats?.monthCompare && viewStats.monthCompare > 0 ? "+" : ""}{viewStats?.monthCompare || 0}%
                      </span>
                    </div>
                  </Col>
                </Row>
              )}
            </Card>
            
            {/* 下方：点赞情况统计 */}
            <Card title="点赞情况统计" bordered>
              {starStatsLoading ? (
                <Skeleton active paragraph={{ rows: 4 }} />
              ) : (
                <Row gutter={16}>
                  <Col span={8}>
                    <Statistic
                      title="今日点赞量"
                      value={starStats?.today || 0}
                      valueStyle={{ color: '#1890ff' }}
                      prefix={<CheckCircleOutlined />}
                    />
                    <div className="view-growth">
                      较昨日: <span className={starStats?.todayCompare && starStats.todayCompare > 0 ? "up" : "down"}>
                        {starStats?.todayCompare && starStats.todayCompare > 0 ? "+" : ""}{starStats?.todayCompare || 0}%
                      </span>
                    </div>
                  </Col>
                  
                  <Col span={8}>
                    <Statistic
                      title="本周点赞量"
                      value={starStats?.week || 0}
                      valueStyle={{ color: '#52c41a' }}
                      prefix={<CheckCircleOutlined />}
                    />
                    <div className="view-growth">
                      较上周: <span className={starStats?.weekCompare && starStats.weekCompare > 0 ? "up" : "down"}>
                        {starStats?.weekCompare && starStats.weekCompare > 0 ? "+" : ""}{starStats?.weekCompare || 0}%
                      </span>
                    </div>
                  </Col>
                  
                  <Col span={8}>
                    <Statistic
                      title="本月点赞量"
                      value={starStats?.month || 0}
                      valueStyle={{ color: '#722ed1' }}
                      prefix={<CheckCircleOutlined />}
                    />
                    <div className="view-growth">
                      较上月: <span className={starStats?.monthCompare && starStats.monthCompare > 0 ? "up" : "down"}>
                        {starStats?.monthCompare && starStats.monthCompare > 0 ? "+" : ""}{starStats?.monthCompare || 0}%
                      </span>
                    </div>
                  </Col>
                </Row>
              )}
            </Card>
          </Col>
        </Row>
      </div>
      
      {/* 可视化区域 */}
      <div className="dashboard-section" style={{ marginTop: '20px' }}>
        <Row gutter={16}>
          <Col span={12}>
            <Card title="新闻状态分布" bordered>
              <div ref={pieChartRef} style={{ height: '300px' }} />
            </Card>
          </Col>
          <Col span={12}>
            <Card title="分类新闻数量" bordered>
              <div ref={barChartRef} style={{ height: '300px' }} />
            </Card>
          </Col>
        </Row>
      </div>
    </div>
  );
};

export default Home;